<template>
  <section class="daterange">
    <el-date-picker
      v-model="value"
      :editable="false"
      value-format="timestamp"
      type="daterange"
      :format="format"
      :clearable="clearable"
      :disabled="disabled"
      :start-placeholder="startplaceholder"
      :end-placeholder="endplaceholder"
      :picker-options="pickeroptions"
      @change="handleChange"
    ></el-date-picker>
  </section>
</template>
<script>
import mixins from './../mixins'
export default {
  name: 'VDateRange',
  mixins: [mixins],
  props: {
    option: {
      type: Object,
      default: {
        rangeOpen: false,
        rangeBefore: null,
        rangeAfter: null,
      }
    }
  },
  computed: {
    type () {
      return this.option.type || 'date'
    },
    startplaceholder () {
      return this.option.startplaceholder || '开始日期'
    },
    endplaceholder () {
      return this.option.endplaceholder || '结束日期'
    },
    format () {
      return this.option.format || 'yyyy-MM-dd'
    },
    rangeOpen () {
      return this.option.rangeOpen
    },
    rangeBefore () {
      return this.option.rangeBefore
    },
    rangeAfter () {
      return this.option.rangeAfter
    },
    pickeroptions () {
      return {
        disabledDate: (time) => {
          if (this.rangeOpen) {
            return time.getTime() < new Date(this.rangeBefore).getTime() || time.getTime() > new Date(this.rangeAfter).getTime()
          } else {
            return false
          }
        }
      }
    }
  },
  data () {
    return {
      t: new Date(),
      value: []
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      if (!this.option.value || this.option.value.length === 0) {
        let t = new Date()
        this.value = [t.getTime(), t.getTime()]
      } else {
        this.value = this.option.value.map(a => this.formatDate(a).getTime());
      }
    },

    getValue () {
      return this.value;
    },

    setValue (v) {
      if (v.length === 2) {
        let [start, end] = v
        start = this.formatDate(start);
        end = this.formatDate(end);
        this.value = [start.getTime(), end.getTime()];
      }
    },

    setCheck () {
      let { value, required } = this
      let error = false, errorMsg = ''
      if (value !== undefined && value !== null) {
        value = value
      }
      if (required && value == null) {
        error = true
        errorMsg = '必填选项不能为空'
      }
      this.error_ = error
      this.error_message_ = errorMsg
      this.fieldCheck()
    },

    formatDate (a) {
      if (!(a instanceof Date)) {
        if (!a) {
          return new Date()
        } else {
          return new Date(a)
        }
      }
      return a
    },

    handleChange (e) {
      this.setCheck()
      this.dispatch_event('filed-value-change', e)
    }
  }
}
</script>
<style lang="scss" scoped>
.daterange {
  /deep/ {
    .el-date-editor {
      width: 100%;
    }
  }
}
</style>